package basiclocaloperator.parsexml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * Created by Administrator on 2017/2/22.
 */
public class Dom4Parse {
    public static void main(String[] args) throws Exception {
//        dom4Test();
        xpathTest();
    }

    private static void dom4Test() throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/xml/book.xml"));
        Element root = document.getRootElement();
        List<Element> booksList = root.elements("书");
        Element book = booksList.get(1);
        System.out.println(book.element("书名").getText());

        Element book2 = root.addElement("书");
        book2.addElement("售价").setText("209元");

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");

        XMLWriter writer = new XMLWriter(new FileOutputStream("src/xml/book.xml"), format);
        writer.write(document);
        writer.close();
    }

    private static void xpathTest() throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/xml/book.xml"));

        List<Node> list = document.selectNodes("//作者");

        for (Node node : list) {
            System.out.println(node.getText());
        }
    }
}
